package com.lxy.cloud.mqtt.client.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.lxy.cloud.mqtt.client.exception.JsonUtilException;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @Author: lxy
 * @Date: 2020/9/7 16:53
 * @Desc: json序列化工具类，禁止使用fastjson!!!
 */
public class JsonUtil {

    private ObjectMapper mapper = new ObjectMapper();

    JsonUtil() {
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static JsonUtil create() {
        return new JsonUtil();
    }


    public JsonUtil setDateFormat(String pattern) {
        mapper.setDateFormat(new SimpleDateFormat(pattern));
        return this;
    }

    public JsonUtil setNamingStrategy(PropertyNamingStrategy propertyNamingStrategy) {
        mapper.setPropertyNamingStrategy(propertyNamingStrategy);
        return this;
    }

    public JsonUtil unwrapRootValue() {
        mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
        return this;
    }

    public JsonUtil wrapRootValue() {
        mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
        return this;
    }

    public JsonUtil setFilterProvider(FilterProvider filterProvider) {
        mapper.setFilterProvider(filterProvider);
        return this;
    }

    public String objectToJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new JsonUtilException("Failed to convert object to json", e);
        }
    }

    public <T> T jsonToObject(String responseJson, Class<T> clazz) {
        try {
            return mapper.readValue(responseJson, clazz);
        } catch (IOException e) {
            throw new JsonUtilException("Failed to convert json to object", e);
        }
    }

    public JsonNode getJsonNode(String jsonStr) {
        try {
            return mapper.readTree(jsonStr);
        } catch (JsonProcessingException e) {
            throw new JsonUtilException("Failed to convert request to JsonNode",
                    e);
        } catch (IOException e) {
            throw new JsonUtilException("IO exception", e);
        }
    }

    /**
     * 进行复杂类型反序列化工作 （自定义类型的集合类型）
     *
     * @param str           源字符串
     * @param typeReference 包含elementType与CollectionType的typeReference
     * @param <T>
     * @return
     */
    public <T> T jsonToObject(String str, TypeReference<T> typeReference) {
        ObjectMapper mapper = new ObjectMapper();
        if (StringUtils.isEmpty(str) || typeReference == null) {
            return null;
        }
        try {
            return (T) mapper.readValue(str, typeReference);
        } catch (IOException e) {
            throw new JsonUtilException("Failed to convert request to JsonNode", e);
        }
    }

}
